# coding=utf-8
#import pandas as pd
import logging
import os
import sys
from os.path import expanduser
from pypinyin import pinyin, Style

reload(sys)
sys.setdefaultencoding('utf-8')
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logger = logging.getLogger(__name__)

'''计算季度净值'''
def calc_netvalue_in_period(df):
    diff_df = df.diff(1)
    def trans_row(row):
        if row.name[4:6] == '03':
            return df.loc[row.name]
        else:
            return row

    df = diff_df.apply(trans_row, axis="columns")
    return df


def get_first_letter(stockName):
    first_letters = pinyin(stockName, style=Style.FIRST_LETTER)
    result = []
    for letter in first_letters:
        result.append(letter[0])
    return "".join(result)

def mkdir(path):
    folder = os.path.exists(path)
    if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(path)  # makedirs 创建文件时如果路径不存在会创建这个路径
    else:
        logger.debug(path + " exist")

#https://www.cnblogs.com/monsteryang/p/6574550.html
def save_to_new_file(filename, content, mode='w'):
    f = open(filename, mode)
    # 第二步：读取文件内容
    f.write(content)
    # 第三步：关闭文件
    f.close()

stock_data_home = expanduser("~")+ "/stock_data_bak/"

def save_finance_data(stock, type, content):
    finance_data_dir = stock_data_home + "/finance_data/"
    mkdir(finance_data_dir)
    file_name = finance_data_dir + stock+"_"+type
    f = open(file_name, 'w')
    f.write(content)
    f.close()
    return file_name

def remove_file(path):
    os.remove(path)

def save_daily_k_data(stock, content):
    daily_k_dir = stock_data_home + "/daily_k/"
    mkdir(daily_k_dir)
    f = open(daily_k_dir + stock, 'a')
    f.write(content)
    f.close()

def bypass_stock(stockCode):
    if len(sys.argv) == 1:
        return False
    startCode = sys.argv[1]
    endCode = sys.argv[2]
    if startCode <= stockCode <= endCode:
        return False
    else:
        return True

#long time to iterator cursor will casue timeout. This method quick iterator cursor
def quick_access_cursor(cursor):
    result = [];
    for item in cursor[:]:
        result.append(item)
    return result;

            #save_to_new_file("test/test", 'fdsfd')
#os.makedirs("dir2/dir2")